package com.skp.shaphan.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.skp.shaphan.sql.ValueToText;


public class ExportDataWriter {
	private File outputFile = null;
	private OutputStream outputStream = null;
	private boolean streamsCreated = false;
	private boolean headingWritten = false;
	private boolean dataWritten = false;
	private boolean oddRow = true;
	
	public ExportDataWriter() {
	}
	
	public void setOutputFile(File outputFile) {
		this.outputFile = outputFile;
	}
	
	private void createStreams() throws IOException {
		if(outputFile == null) {
			outputStream = new ByteArrayOutputStream();
			createStreams(outputStream);
		} else {
			outputStream = new FileOutputStream(outputFile);
			createStreams(outputStream);
		}
		streamsCreated = true;
	}
	
	protected void createStreams(OutputStream stream) throws IOException {
		
	}
	
	public void close() throws IOException {
		outputStream.close();
	}
	
	public String getData() {
		return ((ByteArrayOutputStream)outputStream).toString();
	}
	
	public void writeHeadingCell(String data) throws IOException {
		if(!streamsCreated) {
			createStreams();
		}
		writeHeadingCellData(data);
		headingWritten = true;
		dataWritten = true;
	}
	
	protected void writeHeadingCellData(String data) {
		
	}
	
	public void finishHeadings() {
		
	}
	
	public void writeNewRow() throws IOException {
		if(!streamsCreated) {
			createStreams();
		}
		writeNewRowData();
	}
	
	protected void writeNewRowData() {
		
	}
	
	public void writeCell(Object data, int columnNumber) throws IOException {
		if(!streamsCreated) {
			createStreams();
		}
		try {
			writeCellData(ValueToText.getInstance().convert(data), columnNumber);
		} catch (SQLException e) {
			throw new IOException(e);
		}
		dataWritten = true;
	}
	
	protected void writeCellData(String data, int columnNumber) {
		
	}
	
	public void closeRow() {
		oddRow = !oddRow;
	}

	protected boolean isHeadingWritten() {
		return headingWritten;
	}

	protected boolean isDataWritten() {
		return dataWritten;
	}

	protected boolean isOddRow() {
		return oddRow;
	}

	public void setMetaData(ResultSetMetaData meta) throws SQLException {
	}
}
